package com.sjz.han.industry.activites;

import android.Manifest;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.sjz.han.industry.R;
import com.sjz.han.industry.base.BaseActivity;
import com.sjz.han.industry.entities.BankEntity;
import com.sjz.han.industry.entities.LoignEntity;
import com.sjz.han.industry.entities.PersonEntity;
import com.sjz.han.industry.internetmanage.ReqestUrl;
import com.sjz.han.industry.utils.GlideImageLoader;
import com.sjz.han.industry.utils.JsonUtils;
import com.sjz.han.industry.utils.PicUtils;
import com.sjz.han.industry.utils.ToastUtils;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 提交支付截图
 */
public class UploadPayMsgActivity extends BaseActivity implements View.OnClickListener{
    private ImageView uploand_jietu_img;
    private EditText uppay_name_edt,uppay_phone_edt,uppay_bankname_edt,uppay_bankcode_edt;
    private String name="",phone="",bankname="",bankcode="",adress;
    private Button uppay_sure_btn;
    private File uploadFile=null;

    private TextView bank_name_tv,bank_phone_tv,bank_baname_tv,bank_bcode_tv;
    @Override
    protected int setLayoutId() {
        return R.layout.activity_uploadpaymsg;
    }

    @Override
    protected void initDatas() {
        getBankMsg();
    getMsg();
    }

    @Override
    protected void initViews() {
        reback_btn=(RelativeLayout)this.findViewById(R.id.reback_btn);
        titleTv=(TextView)this.findViewById(R.id.ctitle_tv);
        titleTv.setText("提交资料");

        uploand_jietu_img=(ImageView)this.findViewById(R.id.uploand_jietu_img);

        uppay_name_edt=(EditText)this.findViewById(R.id.uppay_name_edt);
        uppay_phone_edt=(EditText)this.findViewById(R.id.uppay_phone_edt);
        uppay_bankname_edt=(EditText)this.findViewById(R.id.uppay_bankname_edt);
        uppay_bankcode_edt=(EditText)this.findViewById(R.id.uppay_bankcode_edt);

        uppay_sure_btn=(Button)this.findViewById(R.id.uppay_sure_btn);

        bank_name_tv=(TextView)this.findViewById(R.id.bank_name_tv);
        bank_phone_tv=(TextView)this.findViewById(R.id.bank_phone_tv);
        bank_baname_tv=(TextView)this.findViewById(R.id.bank_baname_tv);
        bank_bcode_tv=(TextView)this.findViewById(R.id.bank_bcode_tv);
    }

    @Override
    protected void setLisener() {
        reback_btn.setOnClickListener(this);
        uploand_jietu_img.setOnClickListener(this);
        uppay_sure_btn.setOnClickListener(this);
    }

    @Override
    protected void onRetry() {

    }

    @Override
    public void onClick(View v) {
        name=uppay_name_edt.getText().toString().trim();
        phone=uppay_phone_edt.getText().toString().trim();
        bankname=uppay_bankname_edt.getText().toString().trim();
        bankcode=uppay_bankcode_edt.getText().toString().trim();
        switch (v.getId()){
            case R.id.reback_btn:
                finish();
                break;
            case R.id.uploand_jietu_img:
                PermissionsUtil.requestPermission(this, new PermissionListener() {
                    @Override
                    public void permissionGranted(@NonNull String[] permission) {
                        List<String> pathList = new ArrayList<>();

                        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                                .imageLoader(new GlideImageLoader())
                                .iHandlerCallBack(iHandlerCallBack)
                                .provider("com.sjz.han.industry.fileprovider")
                                .pathList(pathList)
                                .multiSelect(false)
                                .multiSelect(false, 1)
                                .maxSize(1)
                                .crop(false)// 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                                .crop(false, 1, 1, 500, 500) // 配置裁剪功能的参数，   默认裁剪比例 1:1
                                .isShowCamera(true)
                                .filePath("/zijinpans")
                                .build();

                        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(UploadPayMsgActivity.this);
                    }

                    @Override
                    public void permissionDenied(@NonNull String[] permission) {

                    }
                }, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA,
                        Manifest.permission.RECORD_AUDIO});
                break;
            case R.id.uppay_sure_btn:
                if(uploadFile==null){
                    ToastUtils.popUpToast("请上传截图");
                }else  if(TextUtils.isEmpty(name)){
                    ToastUtils.popUpToast("姓名不可为空！");
                }else if(TextUtils.isEmpty(phone)){
                    ToastUtils.popUpToast("手机号不可为空！");
                }else if(TextUtils.isEmpty(bankname)){
                    ToastUtils.popUpToast("银行名称不可为空！");
                }else if(TextUtils.isEmpty(bankcode)){
                    ToastUtils.popUpToast("银行卡号不可为空！");
                }else{
                     uploadMsg();
                }
                break;
        }
    }

    IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
        @Override
        public void onStart() {
        }

        @Override
        public void onSuccess(List<String> photoList) {
            File file = new File(photoList.get(0));
            yasuoimg(file);
            PicUtils.showImg(UploadPayMsgActivity.this, uploand_jietu_img,photoList.get(0));

        }

        @Override
        public void onCancel() {
        }

        @Override
        public void onFinish() {
        }

        @Override
        public void onError() {
        }
    };
    //压缩图片
    public void yasuoimg(File photos){
        Luban.with(UploadPayMsgActivity.this)
                .load(photos)
                .ignoreBy(100)
                .setTargetDir(getPath())
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                        showLoadingDialog("正在压缩图片...");
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        hideLoadingDialog();
                        uploadFile=file;
//                        uploadPhoto(file);
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                        hideLoadingDialog();
                    }
                }).launch();
    }
    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/zijipanhuo/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }
    public void getMsg(){
        showLoadingDialog("正在获取数据...");
        OkHttpUtils
                .post()
                .url(ReqestUrl.PERSONMSG_URL)
                .addParams("token",shareUtils.getToken())
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.popUpToast("请求超时");
            }
            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if(ReqestUrl.rebacRequestJson(response)!=null){
                    PersonEntity entity= JsonUtils.getObject(response,PersonEntity.class);
                    if(entity!=null&&entity.code==0){
                        if(entity.data!=null){
                            setPersonMsg(entity.data);
                        }
                    }else{
                        ToastUtils.popUpToast(entity.msg);
                    }
                }
            }
        });
    }
    public void setPersonMsg(PersonEntity.PersonData entity){
        name=entity.username;
        phone=entity.phone;
        bankname=entity.bankName;
        bankcode=entity.bankCode;
        uppay_name_edt.setText(entity.username);
        uppay_phone_edt.setText(entity.phone);
        uppay_bankname_edt.setText(entity.bankName);
        uppay_bankcode_edt.setText(entity.bankCode);
    }

    public void uploadMsg() {
        showLoadingDialog("正在上传信息...");
        //图片参数，图片名称，图片文件
        final PostFormBuilder builder = OkHttpUtils.post().url(ReqestUrl.UPLOAD_JHMSG_URL);
        if (!uploadFile.exists()) {
            return;
        }
        String filename = uploadFile.getName();
        builder.addFile("file", filename, uploadFile);
        builder.addParams("token",shareUtils.getToken());
        builder.addParams("username",name);
        builder.addParams("phone",phone);
        builder.addParams("bankName",bankname);
        builder.addParams("bankCode",bankcode);
        builder.build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        hideLoadingDialog();
                        ToastUtils.popUpToast("提交失败,请稍后重试!");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        hideLoadingDialog();
                        if(ReqestUrl.rebacRequestJson(response)!=null){
                            LoignEntity entity= JsonUtils.getObject(response,LoignEntity.class);
                            if(entity!=null&&entity.code==0){
                                ToastUtils.popUpToast(entity.msg);
                                finish();
                            }else{
                                ToastUtils.popUpToast(entity.msg);
                            }
                        }

                    }
                });
    }

    public void getBankMsg(){
        OkHttpUtils
                .post()
                .url(ReqestUrl.BANKMSG_URL)
                .addParams("token",shareUtils.getToken())
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.popUpToast("请求超时");
            }
            @Override
            public void onResponse(String response, int id) {
                if(ReqestUrl.rebacRequestJson(response)!=null){
                    BankEntity entity= JsonUtils.getObject(response,BankEntity.class);
                    if(entity!=null&&entity.code==0){
                        if(entity.data!=null){

                            bank_name_tv.setText("姓名："+entity.data.name);
                            bank_phone_tv.setText("联系电话："+entity.data.phone);
                            bank_baname_tv.setText("收款银行："+entity.data.bankname);
                            bank_bcode_tv.setText("收款账号："+entity.data.bankcode);
                        }
                    }else{
                        ToastUtils.popUpToast(entity.msg);
                    }
                }
            }
        });
    }
}
